package cn.gok.server.controller;

import cn.gok.common.config.SystemLog;
import cn.gok.common.entity.goods.Goods;
import cn.gok.common.resp.PageResult;
import cn.gok.common.resp.Result;
import cn.gok.server.service.GoodsService;
import cn.gok.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author: DxlinY
 * @apiNote: 商品控制层
 * @date: 2020/11/4
 * @time: 17:50
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;


    /**
     * 商品模块分页
     *
     * @param page  页数
     * @param limit 页容量
     * @return pageResult
     */
    @PostMapping("/page")
    @SystemLog(model = "商品模块", method = "商品分类")
    public PageResult listAll(int page, int limit, Goods goods) {
        return ResultUtil.pageInfo(goodsService.listAll(page, limit, goods));
    }

    /**
     * 批量删除
     *
     * @param request
     * @return result
     */
    @PostMapping("/delByIds")
    @SystemLog(model = "商品模块", method = "批量删除")
    public Result delByIds(HttpServletRequest request) {
        String[] ids = request.getParameterValues("ids");
        List <String> idsStr = Stream.of(ids).collect(Collectors.toList());
        if (goodsService.delById(idsStr) > 0) {
            return ResultUtil.success(null);
        }
        return ResultUtil.error(null);
    }

    /**
     * 添加商品
     *
     * @param goods 商品实体类
     * @return result
     */
    @PostMapping("/insert")
    @SystemLog(model = "商品模块", method = "添加")
    public Result insert(Goods goods) {
        if (goodsService.add(goods) > 0) {
            return ResultUtil.success(null);
        }
        return ResultUtil.error(null);
    }


    /**
     * 获取商品
     *
     * @param goodsId 商品编号
     * @return
     */
    @PostMapping("/getById")
    @SystemLog(model = "商品模块", method = "获取商品")
    public Result getById(String goodsId) {
        return ResultUtil.success(goodsService.getById(goodsId));
    }

    /**
     * 修改
     *
     * @param goods 商品对象
     * @return result
     */
    @PostMapping("/updateById")
    @SystemLog(model = "商品模块", method = "修改")
    public Result updateById(Goods goods) {
        if (goodsService.updateById(goods) > 0) {
            return ResultUtil.success(null);
        }
        return ResultUtil.error(null);
    }
}
